package com.unitd.frame.comm.utils.encrypt;

import com.unitd.frame.comm.utils.CharsetUtils;
import com.unitd.frame.comm.utils.ExceptionUtils;
import com.unitd.frame.comm.utils.encrypt.base64.Base64Util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 基于RSA公钥算法的公钥/私钥/签名工具类
 * https://baike.baidu.com/item/RSA%E7%AE%97%E6%B3%95/263310?fr=aladdin 百度百科
 * RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)一起提出的.
 * RSA算法基于一个十分简单的数论事实：将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥.
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密
 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 * @filename RSA.java
 * @copyright www.pactera.com.cn
 * @author Hudan
 * @version 1.0
 * @date 2016/10/27
 */
public class RSA {

	/** 加密算法类型:RSA */
	private static final String KEY_ALGORITHM = "RSA";
	/** 签名算法(MD5和RSA) */
	private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	/** 公钥的key */
	private static final String PUBLIC_KEY = "RSAPublicKey";
	/** 私钥的key */
	private static final String PRIVATE_KEY = "RSAPrivateKey";
	/** RSA密钥长度必须是64的倍数,在512~65536之间.默认是1024 */
	private static final int KEY_SIZE = 1024;
	/** RSA最大加密明文大小:明文长度(bytes) <= 密钥长度(bytes)-11 		117 */
	private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11;
	/** RSA最大解密密文大小 */
	private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8;

	/**
	 * @desc 生成密钥对(公钥和私钥)
	 * @return 密钥对
	 */
	public static Map<String, Object> genKeyPair() {
		try {
			// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

			// 初始化密钥对生成器,密钥大小为96-1024位
			keyPairGen.initialize(KEY_SIZE, new SecureRandom());
			// 生成一个密钥对,保存在keyPair中
			KeyPair keyPair = keyPairGen.generateKeyPair();
			// 得到公钥
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
			// 得到私钥
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

			// 将生成的密钥对,保存在 keyMap 中
			Map<String, Object> keyMap = new HashMap<>(2);
			keyMap.put(PUBLIC_KEY, publicKey);
			keyMap.put(PRIVATE_KEY, privateKey);
			return keyMap;
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked(e);
		}
	}

	/**
	 * @desc 用私钥对信息生成数字签名
	 * @param data       已加密数据
	 * @param privateKey 私钥(BASE64编码)
	 * @return 数字签名
	 */
	public static String sign(byte[] data, String privateKey) {
		try {
			byte[] keyBytes = Base64Util.decode(privateKey);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initSign(privateK);
			signature.update(data);
			return Base64Util.encode(signature.sign());
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (SignatureException e) {
			throw ExceptionUtils.unchecked("数字签名非法");
		} catch (InvalidKeyException e) {
			throw ExceptionUtils.unchecked("加密私钥非法,请检查");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}

	/**
	 * @desc 利用公钥校验数字签名
	 * @param data      已加密数据
	 * @param publicKey 公钥(BASE64编码)
	 * @param sign      数字签名
	 * @return 进行校验之后的数字签名
	 */
	public static boolean verify(byte[] data, String publicKey, String sign) {
		byte[] keyBytes = Base64Util.decode(publicKey);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			PublicKey publicK = keyFactory.generatePublic(keySpec);
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initVerify(publicK);
			signature.update(data);
			return signature.verify(Base64Util.decode(sign));
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (SignatureException e) {
			throw ExceptionUtils.unchecked("数字签名非法");
		} catch (InvalidKeyException e) {
			throw ExceptionUtils.unchecked("加密私钥非法,请检查");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}

	/**
	 * @desc 获取私钥
	 * @param keyMap 密钥对
	 * @return BASE64编码的私钥
	 */
	public static String getPrivateKey(Map<String, Object> keyMap) {
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		return Base64Util.encode(key.getEncoded());
	}

	/**
	 * @desc 根据私钥将相应的字符串进行加密
	 * @param privateKey 私钥(BASE64编码)
	 * @param plainData 需要加密的字符数组
	 * @return 加密后的私钥
	 */
	public static byte[] encryptByPrivateKey(String privateKey, byte[] plainData) {
		try {
			byte[] keyBytes = Base64Util.decode(privateKey);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

			Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

			// 执行加密处理
			return encryptByData(keyFactory, privateK, plainData);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}

	/**
	 * @desc 根据私钥将相应的密文进行解密
	 * @param privateKey    私钥(BASE64编码)
	 * @param encryptedData 已加密数据
	 * @return 解密后的私钥
	 */
	public static byte[] decryptByPrivateKey(String privateKey, byte[] encryptedData) {
		try {
			byte[] keyBytes = Base64Util.decode(privateKey);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

			Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

			// 执行解密处理
			return decryptByByData(keyFactory, privateK, encryptedData);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}

	/**
	 * @desc 根据私钥将相应的密文进行解密
	 * @param privateKey    私钥(BASE64编码)
	 * @param encryptedData 已加密数据
	 * @return 解密后的私钥
	 */
	public static byte[] decryptByPrivateKey(PrivateKey privateKey, byte[] encryptedData) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

			return decryptByByData(keyFactory, privateKey, encryptedData);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		}
	}

	/**
	 * @desc 获取公钥
	 * @param keyMap 密钥对
	 * @return BASE64编码的公钥
	 */
	public static String getPublicKey(Map<String, Object> keyMap) {
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		return Base64Util.encode(key.getEncoded());
	}

	/**
	 * @desc 根据公钥将相应的字符串进行加密
	 * @param publicKey 公钥
	 * @param plainText 需要加密的字符串
	 * @return byte
	 */
	public static String encryptByPublicKey(PublicKey publicKey, String plainText) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			byte[] data = plainText.getBytes();

			// 执行加密操作,获取密文
			byte[] encryptedData = encryptByData(keyFactory, publicKey, data);

			return new String(encryptedData, CharsetUtils.UTF_8);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		}
	}

	/**
	 * @desc 根据公钥将相应的字符数组进行加密
	 * @param publicKey 公钥(BASE64编码)
	 * @param data      源数据
	 * @return 密文
	 */
	public static byte[] encryptByPublicKey(String publicKey, byte[] data) {
		try {
			byte[] keyBytes = Base64Util.decode(publicKey);
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key publicK = keyFactory.generatePublic(x509KeySpec);

			// 执行加密操作,获取密文
			return encryptByData(keyFactory, publicK, data);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}

	/**
	 * @desc 公钥解密
	 * @param encryptedData 已加密数据
	 * @param publicKey     公钥(BASE64编码)
	 * @return 解密后的公钥
	 */
	public static byte[] decryptByPublicKey(String publicKey, byte[] encryptedData) {
		try {
			byte[] keyBytes = Base64Util.decode(publicKey);
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key publicK = keyFactory.generatePublic(x509KeySpec);

			return decryptByByData(keyFactory, publicK, encryptedData);
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeySpecException e) {
			throw ExceptionUtils.unchecked("密钥非法");
		}
	}
	/**
	 * @desc 根据加密对象和公钥对象以及需要加密的数据,将数据进行加密
	 * @param keyFactory 加密对象
	 * @param publicKey 公钥对象
	 * @param data 需要加密的数据
	 * @return 加密后的密文
	 */
	private static byte[] encryptByData(KeyFactory keyFactory, Key publicKey, byte[] data) {
		ByteArrayOutputStream out = null;

		try {
			// 对数据加密
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			int inputLen = data.length;
			out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
			return out.toByteArray();
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeyException e) {
			throw ExceptionUtils.unchecked("加密私钥非法,请检查");
		} catch (NoSuchPaddingException e) {
			throw ExceptionUtils.unchecked("没有相应的密文数据");
		} catch (BadPaddingException e) {
			throw ExceptionUtils.unchecked("密文数据已损坏");
		} catch (IllegalBlockSizeException e) {
			throw ExceptionUtils.unchecked("非法的代码块");
		} finally {
			try {
				if (out != null) out.close();
			} catch (Exception e) {
				throw ExceptionUtils.unchecked(e);
			}
		}
	}

	/**
	 * @desc 根据加密对象和公钥对象以及需要加密的数据,将数据进行加密
	 * @param keyFactory 加密对象
	 * @param key 公钥/私钥对象
	 * @param encryptedData 需要解密的加密数据
	 * @return 加密后的密文
	 */
	private static byte[] decryptByByData(KeyFactory keyFactory, Key key, byte[] encryptedData) {

		ByteArrayOutputStream out = null;
		try {
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, key);
			int inputLen = encryptedData.length;
			out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
			return out.toByteArray();
		} catch (NoSuchAlgorithmException e) {
			throw ExceptionUtils.unchecked("无此解密算法");
		} catch (InvalidKeyException e) {
			throw ExceptionUtils.unchecked("解密私钥非法,请检查");
		} catch (NoSuchPaddingException e) {
			throw ExceptionUtils.unchecked("没有相应的密文数据");
		} catch (BadPaddingException e) {
			throw ExceptionUtils.unchecked("密文数据已损坏");
		} catch (IllegalBlockSizeException e) {
			throw ExceptionUtils.unchecked("非法的代码块");
		} finally {
			try {
				if (out != null) out.close();
			} catch (Exception e) {
				throw ExceptionUtils.unchecked(e);
			}
		}
	}

	/**
	 * @desc 从KeyStore获取公钥
	 * @desc 根据keyStore
	 * @param keyStore 密钥对象
	 * @param alias 别名
	 * @param keyPass 密钥内容解密密钥
	 * @return 公钥对象
	 */
	public static PublicKey loadPublicKeyFromKeyStore(KeyStore keyStore, String alias, String keyPass) {
		try {
			RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
			RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
					key.getPublicExponent());
			return KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
		} catch (Exception e) {
			throw ExceptionUtils.unchecked("从KeyStore获取公钥失败:" + e.getLocalizedMessage());
		}
	}

	/**
	 * @desc 从KeyStore获取私钥
	 * @param location 密钥文件存储在当前服务所在机器的位置
	 * @param alias 别名
	 * @param storeType key类型
	 * @param storePass key文件解密密钥
	 * @param keyPass 密钥内容解密密钥
	 * @return 私钥对象
	 */
	public static PrivateKey loadPrivateKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
		try {
			storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
			keyPass = keyPass == null ? storePass : keyPass;
			KeyStore keyStore = KeyStore.getInstance(storeType);
			InputStream is = new FileInputStream(location);
			keyStore.load(is, storePass.toCharArray());
			// 由密钥库获取密钥的两种方式
			return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
		} catch (Exception e) {
			throw ExceptionUtils.unchecked("从KeyStore获取私钥失败:" + e.getLocalizedMessage());
		}
	}
}